<template>
  <el-main class="bg table_wrap fresh_products">
    <div class='div-form'>
      <el-form ref="elFormRef" :model="formInline" label-width="90px" :style="{ width: '100%' }" label-position="left">
        <el-row :gutter="20">
		  <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
			<el-form-item label="标题">
			  <el-input v-model="formInline.cart_title"></el-input>
			</el-form-item>
		  </el-col>
		  <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
			<el-form-item label="分类">
			  <el-select v-model="formInline.cart_type">
				<el-option :key="-1" :value="''" :label="'无'"></el-option>
				<el-option v-for="(o,i) in list_goods_cart_type" :key="i" :value="o.name" :label="o.name"></el-option>
			  </el-select>
			</el-form-item>
		  </el-col>
						<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="商品编号">
								<el-input v-model="formInline.product_code"></el-input>
							</el-form-item>
			</el-col>
														<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="店铺名称">
								<el-input v-model="formInline.store_name"></el-input>
							</el-form-item>
			</el-col>
						<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="支付状态">
					<el-select v-model="formInline.pay_state">
						<el-option value="">全部</el-option>
						<el-option value="未支付">未支付</el-option>
						<el-option value="已支付">已支付</el-option>
					</el-select>
				</el-form-item>
			</el-col>
        </el-row>
      </el-form>
    </div>
    <baseTable :tableColumns="columns" requestApi='/api/fresh_products/get_list' :isShowSelect="true" :vm="vm"
               v-model:isRefresh="isRefresh" :otherParams="formInline"
               @handleSelectionChange="handleSelectionChange"
               @handleCurrentChangeNew="handleCurrentChangeNew"
    >
      <!-- 头部按钮 -->
      <template #baseHeadFunt>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="onReset(true)">重置</el-button>
        <el-button v-if="$check_option('/fresh_products/table', 'print')"@click="print('dataTable')"class="search_btn_print">打印</el-button>
        <el-button
            v-if="$check_action('/fresh_products/table','del') || $check_action('/fresh_products/view','del')"
            class="search_btn_del" type="danger" @click="delInfo()">删除
        </el-button>
      </template>
      <!-- 操作 -->
      <template #baseTableFunt="{ scope }">
        <el-button type="primary" v-if="user_group == '管理员' || $check_action('/fresh_products/table','set')" size="small"
                    @click="router.push('./view?fresh_products_id='+scope.row.fresh_products_id)">详情
        </el-button>
      </template>
      <template #baseTableFunt2="{ scope }">
        <el-button type="primary" v-if="user_group == '管理员' || $check_action('/fresh_products/table','set')" size="small"
            @click="router.push('./view?fresh_products_id='+scope.fresh_products_id)">详情
        </el-button>
      </template>
      <template #tableContent="{ scope, column }">
        <span v-if="column.prop === 'cart_img'">
			<el-image
                :preview-teleported="true"
                style="width: 60px; height: 60px"
                :src="$fullUrl($banseUrl,scope.row.cart_img)"
                :preview-src-list="[$fullUrl($banseUrl,scope.row.cart_img)]"
                :initial-index="0"
                fit="cover">
           </el-image>
        </span>
                            <span v-if="column.prop === 'seller_customers'">{{ scope.row['seller_customers']?getObj(list_user_seller_customers,scope.row['seller_customers']).nickname+"-"+getObj(list_user_seller_customers,scope.row['seller_customers']).username:"" }}</span>
                      <span v-if="column.prop === 'create_time'">{{formatDate(scope.row.create_time)}}</span>
        <span v-if="column.prop === 'update_time'">{{formatDate(scope.row.update_time)}}</span>
      </template>

      <template #tableContent2="{ scope, column }">

        <span v-if="column.prop === 'create_time'"> {{ column.label }}：{{formatDate(scope.create_time)}}</span>
        <span v-if="column.prop === 'update_time'"> {{ column.label }}：{{formatDate(scope.update_time)}}</span>
      </template>
    </baseTable>
          </el-main>
</template>
<script setup>
  import {useRouter} from "vue-router";

  let router = useRouter();
  import {
          $get_auth,
          func,
          paramsFun,
          $fullUrl,
          formatDate,
          $banseUrl,
          $check_action,
          $toTime,
  } from "@/utils/utils.js";
  import { $post, $get } from "@/api/Api.js";
  import {Picture} from "@element-plus/icons-vue";
  import {ElMessage} from "element-plus";
  import {ref, toRefs, computed, onMounted} from "vue"
  import storageHelper from '@/libs/StorageHelper'

  let user_group = storageHelper.getUserInfo().user_group;
  let table = ref("fresh_products")
  let field = ref("fresh_products_id")
  let url_get_list = ref("/api/fresh_products/get_list")
  let url_del = ref("/api/fresh_products/del")
  // 头部搜索// 搜索
  let formInline = ref({
          "product_code": "",
                    "store_name": "",
          "orderby": `create_time desc`
  })
                        // 用户列表
  let list_user_seller_customers=ref([])
  //商城卖家用户列表
  let get_list_user_seller_customers= async() =>{
    let json = await $get("/api/user/get_list?user_group=商家用户");
    if(json.result){
      list_user_seller_customers.value = json.result.list;
    }
    else if(json.error){
      console.error(json.error);
    }
  }
        //打印开始
  let print = (tableid) => {
    let win = window.open("");
    let tableToPrintA = document.getElementById(tableid);
    win.document.write(tableToPrintA.outerHTML);
    win.document.write("</div></body></html>");
    win.document.close();
    win.focus();
    win.print();
    win.close();
  };
  let vm = ref({
    id: "fresh_products_id"
  })
  // 列名
  const columns =[
    {"prop": "cart_title", "label": "标题",fieldType:1},
    {"prop": "cart_img", "label": "封面图",fieldType:4},
    {"prop": "cart_price", "label": "卖价",fieldType:1},
    {"prop": "cart_price_ago", "label": "原价",fieldType:1},
    {"prop": "cart_inventory", "label": "商品库存",fieldType:1},
    {"prop": "cart_type", "label": "产品分类",fieldType:1},
    {"prop": "cart_description", "label": "描述",fieldType:1},
          {"prop": "product_code", "label": "商品编号",fieldType:1},
                {"prop": "order_rules", "label": "下单规则",fieldType:1},
                {"prop": "seller_customers", "label": "卖家用户",fieldType:2},
                {"prop": "store_name", "label": "店铺名称",fieldType:1},
          {"prop": "create_time", "label": "创建时间",fieldType:3},
    {"prop": "update_time", "label": "更新时间",fieldType:3},
  ]
  // 刷新table
  let isRefresh = ref(false)
  //批量勾选数据框
  let selectList = ref([])
  //点击数据
  let currentRowTableProduct = ref({})
  // 商品分类
  let list_goods_cart_type = ref([])
  let showModal = ref(false)
          // 关闭弹框
  let closeModal = () => {
    showModal.value = false;
  };
  //表格勾选回调
  let handleSelectionChange = (val) => {
    console.log(val)
    selectList.value = val.map((item) => {
      if (item.fresh_products_id !== undefined) {
        return item.fresh_products_id
      } else {
        return item
      }
    })
  }
  //点击当前行
  let handleCurrentChangeNew = (val) => {
    currentRowTableProduct.value = val
  }

  // 搜索
  let onSubmit = () => {
    isRefresh.value = true
  }
  // 重置
  let onReset = (refresh) => {
    formInline.value = {
                  "product_code": "",
                                      "store_name": "",
                  "create_time": "",
      "orderby": `create_time desc`
    }
    isRefresh.value = refresh
  }
  // 批量删除删除
  let delInfo = () => {
    ElMessageBox.confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          selectList.value.map((item) => {
            delFun(item)
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
  }
  // 调用删除方法
  let delFun = (id) => {
          $get(url_del.value, {fresh_products_id: id}).then((json) => {
      if (json.result) {
        let param = {
          source_table: "fresh_products",
          source_field: field.value,
          source_id: id
        }
         $get('/api/goods/del', param).then((json) => {
          if (json.result) {
            isRefresh.value = true;
            ElMessage.success('删除成功');
          } else if (json.error) {
            ElMessage.error(json.error.message);
          }
        });
      } else if (json.error) {
        ElMessage.error(json.error.message);
      }
      isRefresh.value = true
    });
  }
  //获取商品分类
  let get_goods_cart_type = async () => {
    let json = await $get("/api/goods_type/get_list");
    if (json.result) {
      list_goods_cart_type.value = json.result.list;
    } else if (json.error) {
      console.error(json.error);
    }
  }
  let get_list_before = () => {
    if(user_group != "管理员"){
              let sqlwhere = "(";
                                                                          if(user_group=="商家用户"){
                sqlwhere+= "seller_customers = " + this.user.user_id + " or ";
              }
                                                  if (sqlwhere.length>1){
            sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
            sqlwhere += ")";
            formInline.value["sqlwhere"] = sqlwhere;
          }
        }
  }
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    if (obj) {
        return obj;
    } else {
        return "-";
    }
  };
  onMounted(() => {
    get_list_before()
    get_goods_cart_type()
                      get_list_user_seller_customers()
        })
</script>
<style lang="less" scoped>
  .div-form {
    padding: 10px;
  }
</style>